import React, { useRef, useState } from 'react'
import { PlusOutlined, VerticalAlignBottomOutlined, VerticalAlignMiddleOutlined } from '@ant-design/icons'
import { Button, Image, message, Switch, Upload } from 'antd'
import ProTable from '@ant-design/pro-table'
import { PageContainer } from '@ant-design/pro-layout'
import { changePermission, getPeople, manyImp, templateDownload } from '@/services/people'
import CreateOrEdit from './components/CreateOrEdit'
import Reset from './components/Reset'
import GetTime from '@/components/GetTime'
import ProTableConfig from '@/pages/Report/ProTableConfig'

const Index = () => {
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [codeModalShow, setCodeModalShow] = useState(false)
  const [userinfo, setUserinfo] = useState([])
  const [code, setCode] = useState([])
  const [treeData, setTreeData] = useState([])
  // 设置编辑用户的id
  const [editId, setEditId] = useState(undefined)
  // 获取用户头像地址
  const [UserUrl, setUserUrl] = useState(undefined)
  // 表格的ref  操作表格
  const actionRef = useRef()
  /**
   * 添加用户的模态框的关闭和打开
   * @param flag
   * @param id
   * @constructor
   */
  const modalIsShow = (flag, id = undefined) => {
    setIsModalVisible(flag)
    setEditId(id)
  }
  /**
   * 重置密码的模态框的关闭和打开
   */
  const resetModal = (flag) => {
    setCodeModalShow(flag)
  }
  /**
   * 重置密码
   * @param uid
   * @returns {Promise<void>}
   */
  const resetCode = async (uid) => {
    // 打开模态框
    resetModal(true)
    setCode({
      id: uid,
    })
  }
  /**
   * 获取用户数据列表
   */

  const getPeopleList = async (params) => {
    // 更改默认属性名 current
    params = JSON.parse(JSON.stringify(params).replace(/current/g, 'page'))
    const peopleList = await getPeople(params)
    return {
      data: peopleList.data,
      message: 'success',
      total: peopleList.meta.pagination.total,
    }
  }
  /**
   * 禁用启用用户
   * @param uid
   * @returns {Promise<void>}
   */
  const changeStatus = async (uid) => {
    const statusRes = await changePermission(uid)
    if (statusRes.status === undefined) {
      message.success('修改成功')
    }
  }
  /**
   * 模板的下载
   */
  const downLoad = async () => {
    // 获取二进制文件
    const response = await templateDownload()
    // 创建Blob对象
    const url = window.URL.createObjectURL(new Blob([response], { type: 'application/x-xls' }))
    // 创建 a 标签
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', 'user.model.xlsx')
    document.body.appendChild(link)
    // 手动触发事件
    link.click()
    document.body.removeChild(link)
  }
  // 获取域名地址
  {
    localStorage.setItem('domain', 'http://exam.hks.cool')
  }
  let name = localStorage.getItem('domain')

 // 批量导入时执行的回调
  const onChange = ({ file }) => {
    console.log(file)
    if (file.status === 'done') {
      message.success('批量导入成功')
      actionRef.current.reload()
    }
  }

  /**
   * 用户头像地址
   */
  const onUserUrl = url => {
    setUserUrl(url)
  }
  /**
   * 定义字段
   */
  const columns = [
    {
      dataIndex: 'id',
      title: 'ID',
      hideInSearch: true,
    },
    {
      dataIndex: 'name',
      title: '用户名',
    },
    {
      dataIndex: 'avatar_url',
      title: '用户头像',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <Image
            width={50}
            src={_}
            style={{ borderRadius: '50%' }}
            fallback=""
          />
        )
      }
    },
    {
      dataIndex: 'username',
      title: '登录名',
      hideInSearch: true
    },
    {
      dataIndex: 'email',
      title: '邮箱',
    },
    {
      dataIndex: 'phone',
      title: '手机号',
    },
    {
      dataIndex: 'status',
      title: '状态',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <Switch
            checkedChildren="启用"
            unCheckedChildren="禁用"
            defaultChecked={record.status === 1}
            onChange={() => {changeStatus(record.id)}}
          />
        )
      }
    },
    {
      title: '操作',
      render: (_, record) => [
        <Button
          type="primary"
          key={1}
          size={'small'}
          onClick={() => {modalIsShow(true, record.id)}}
          style={{ marginRight: '10px' }}
        >
          编辑
        </Button>,
        <Button
          type="danger"
          key={2}
          size={'small'}
          onClick={() => {resetCode(record.id)}}
        >
          重置密码
        </Button>
      ]
    },
  ]
  return (
    <PageContainer header={{
      extra: [
        <GetTime key="getTime"/>
      ]
    }}>
      <ProTable
        {
          ...ProTableConfig
        }
        columns={columns}
        actionRef={actionRef}
        editable={{
          type: 'multiple',
        }}
        request={(params = {}) => getPeopleList(params)}
        search={{
          labelWidth: 'auto',
        }}
        headerTitle="用户数据"
        toolBarRender={() => [
          <Button onClick={() => {modalIsShow(true)}}
                  key="button" icon={<PlusOutlined/>}
                  type="primary">
            新建
          </Button>,
          <Button
            icon={<VerticalAlignBottomOutlined/>} onClick={() => {downLoad()}}
            key="button"
            type="primary"
          >
            模板下载
          </Button>,

          <Upload
            showUploadList={false}
            accept=".xlsx"
            name="file"
            action={name + '/api/admin/users/import'}
            actionRef={actionRef}
            // beforeUpload={batchImport}
            onChange={onChange}
            headers={{
              Authorization: 'Bearer ' + localStorage.getItem('access_token')
            }}>

            <Button icon={<VerticalAlignMiddleOutlined/>}>批量导入</Button>
          </Upload>,
        ]}
      />
      {
        isModalVisible ? <CreateOrEdit
          isModalVisible={isModalVisible}
          modalIsShow={modalIsShow}
          userinfo={userinfo}
          actionRef={actionRef}
          treeData={treeData}
          editId={editId}
        /> : ''
      }
      {
        codeModalShow ? <Reset
          codeModalShow={codeModalShow}
          resetModal={resetModal}
          code={code}
        /> : ''
      }
    </PageContainer>
  )
}
export default Index

